<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>login</title>
    <link rel="stylesheet" href="../../style/login/login.css">
    <link rel="short cut" href="../../favicon.ico"/>
    <script type="text/javascript" src="../../plugins/jQuery/jquery-3.6.0.js"></script>
    <script type="text/javascript" src="../../plugins/vue/vue.js"></script>
    <script type="text/javascript" src="../../plugins/axios/axios.js"></script>
    <script type="text/javascript" src="../../plugins/layer-master/src/layer.js"></script>
</head>

<body>
<div id="app">
    <form id="form" method="post">
        <h1 id="loginMsg">登 陆</h1>
        <label style="color: red">{{error}}</label>
        <p><label for="username">Username:</label>
            <input id="username" name="username" type="text" v-model="username"
                   autocomplete="off">
        </p>

        <p><label for="password">Password:</label>
            <input id="password" name="password"
                   type="password" v-model="password"></p>
        <div id="subDiv">
            <input type="button" class="loginButton" value="登陆" @click="login">
            <input type="reset" class="button" value="重置">&nbsp;&nbsp;&nbsp;
            <a href="../login/register.html">立即注册</a>
        </div>
    </form>
</div>

<script type="text/javascript">
    // 禁用Vue开发提示1
    Vue.config.productionTip = false;

    new Vue({
        el: '#app',
        data: () => ({
            username: '',
            password: '',
            error: '',
            isLoading: false
        }),
        methods: {
            login() {
                this.error = '';

                // 统一去除首尾空格
                const username = this.username.trim();
                const password = this.password.trim();

                // 基础验证
                if (!username) {
                    this.error = '请输入用户名';
                    return;
                }
                if (!password) {
                    this.error = '请输入密码';
                    return;
                }

                this.isLoading = true;

                // 编码特殊字符（兼容中英文）
                const encodedUsername = encodeURIComponent(username)
                    .replace(/%/g, '!')  // 防止后端二次解码
                    .replace(/'/g, "%27");

                axios.get('http://localhost:8080/user/login', {
                    params: {
                        username: encodedUsername,
                        password: password
                    }
                })
                    .then(resp => {
                        const result = resp.data;
                        console.debug('API响应:', result); // 调试日志

                        if (!result || typeof result.success !== 'boolean') {
                            throw new Error('无效的服务器响应');
                        }

                        if (result.success) {
                            this.handleLoginSuccess(result.data);
                        } else {
                            this.handleLoginFailure(result.error || '用户名或密码错误');
                        }
                    })
                    .catch(error => {
                        console.error('请求失败:', error);
                        this.error = error.response?.data?.message ||
                            error.message ||
                            '网络连接异常，请检查网络';
                    })
                    .finally(() => {
                        this.isLoading = false;
                    });
            },

            handleLoginSuccess(userData) {
                // 严格数据校验
                if (!userData || typeof userData.role !== 'number') {
                    console.error('无效用户数据:', userData);
                    this.error = '用户信息异常，请联系管理员';
                    return;
                }

                // 会话存储
                sessionStorage.setItem('auth', JSON.stringify({
                    id: userData.id,
                    userId: userData.userid,
                    username: userData.username,
                    role: userData.role,
                    timestamp: Date.now()
                }));

                // 跳转逻辑
                const roleMap = {
                    0: 'http://localhost:63343/baowenlishixi_1/front/pages/student/student.html',
                    1: 'http://localhost:63343/baowenlishixi_1/front/pages/teacher/teacher.html',
                    2: 'http://localhost:63343/baowenlishixi_1/front/pages/admin/admin.html'
                };

                const target = roleMap[userData.role];
                if (target) {
                    console.log('跳转至:', target);
                    window.location.href = target;
                } else {
                    this.error = '系统错误：未知用户角色';
                    sessionStorage.removeItem('auth');
                }
            },

            handleLoginFailure(errorMsg) {
                this.error = errorMsg;
            }
        }
    })
</script>
</body>
</html>